<?php

session_start();
$_SESSION['seccode'] = "";
$width = 45;//图片长度
$height = 16;//图片高度
$len = 4;//验证码长度
$noise = true;//是否生成杂点
$noisenum = 80;//杂点数量
$border = true;//边框
$bordercolor = '#000000';
$bgcolor = "#d6e3ef";//背景色
$image = imagecreate($width,$height);
$back = getcolor($bgcolor);
imagefilledrectangle($image,0,0,$width,$height,$back);
$size = $width/$len;
if($size>$height) $size=$height;
$left = ($width-$len*($size+$size/10))/$size;
$code = random($len);
$codecolor = imagecolorallocate($image, 0, 0, 0);
imagestring($image, $size, 4, 0, $code, $codecolor);
if($noise == true) setnoise();
$_SESSION['seccode'] = $code;


if($border) imageRectangle($image, 0, 0, $width-1, $height-1, getcolor($bordercolor));
header("Content-type: image/png");
echo imagePng($image);
imagedestroy($image);

function getcolor($color)
{
     global $image;
     $color = eregi_replace ("^#","",$color);
     $r = $color[0].$color[1];
     $r = hexdec ($r);
     $b = $color[2].$color[3];
     $b = hexdec ($b);
     $g = $color[4].$color[5];
     $g = hexdec ($g);
     $color = imagecolorallocate ($image, $r, $b, $g); 
     return $color;
}
function random($length) {
	$str = 'ABCDEFGHJKLMNOPQRSTUVWXYZ23456789';
	$hash = '';
	for($i = 0; $i < $length; $i++) {
		$hash .= $str[mt_rand(0,32)];
	}
	return $hash;
}
function setnoise()
{
	global $image, $width, $height, $back, $noisenum;
	for ($i=0; $i<$noisenum; $i++){
		$randColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));  
		imagesetpixel($image, rand(0, $width), rand(0, $height), $randColor);
	} 
}
?>